#include "basic.h"
#include "ui.h"
#include "main_interface.h"


//==============================================================================DATA
#if 0
typedef struct ui{
	void *handle;
	void * (*thread)( void *arg );
	pthread_t thread_id;
}ui_s;
#endif
static ui_s ui = {NULL};


static int ui_install( char *ui_name, ui_s *ui );
static int ui_uninstall( ui_s *ui );
//==============================================================================MAIN INTERFACE
pthread_t ui_init()
{
	if( ui_install( context.ui, &ui ) == EXIT_FAILURE )
		exit(-1);
	
	int e = pthread_create( &(ui.thread_id), NULL, ui.thread, NULL );
	assert( !e || !ui.thread_id );
	
	printf("\nUI Thread Start...\n");
	return ui.thread_id;
}

void ui_exit()
{
	ui_uninstall( &ui );
}

//------------------------------------------------------------------------------DATA INTERFACE
char *UI_lib( int offset )
{
	return context.libs_ui[offset];
}

char *UI_lib_default()
{
	return context.ui;
}

//==============================================================================FUNCTION
static int ui_install( char *ui_name, ui_s *ui )
{
	void *handle = NULL, *func = NULL;

	char _ui_name[512] = "\0";
	strcpy( _ui_name, context.lib_dir );
	strcat( _ui_name, ui_name );
	
	handle = dlopen( _ui_name, RTLD_NOW | RTLD_GLOBAL );
	if( handle ) ui->handle = handle;
	else goto error;

	func = dlsym( handle, "thread" );
	if( func == NULL ) goto error;
	else ui->thread = func;
	func = NULL;

	return EXIT_SUCCESS;
	
error:
	printf( "\nERROR: %s", dlerror() );
	return EXIT_FAILURE;
}

static int ui_uninstall( ui_s *ui )
{
	if( ui->handle ) dlclose( ui->handle );
	return EXIT_SUCCESS;
}
